from flask import Flask, render_template, request, redirect, url_for, session
from werkzeug.utils import secure_filename
import secrets
import os

from src.utils import parse_invoice
from src.hamdle_gnucash.piecash import get_accounts, add_transaction_from_dict

app = Flask(__name__)
app.secret_key = secrets.token_hex(16)  # 生成随机密钥
app.config["UPLOAD_FOLDER"] = "uploads"


@app.route("/")
def index():
    accounts = get_accounts()
    session["accounts"] = accounts
    return render_template("index.html", accounts=accounts)


@app.route("/upload", methods=["POST"])
def upload_file():
    if "file" not in request.files:
        return render_template("index.html", error="No file uploaded")

    file = request.files["file"]
    if file.filename == "":
        return render_template("index.html", error="Empty filename")

    # 保存文件
    filename = secure_filename(file.filename)
    filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
    file.save(filepath)

    # 解析发票
    result = parse_invoice(filepath)
    # 将解析结果保存到session
    session["invoice_data"] = result  # 保存到 Session
    # TODO 处理上传的文件，可以发送到一个固定的地方
    os.remove(filepath)  # 清理文件

    return render_template("index.html", result=result, accounts=session["accounts"])


@app.route("/add_transaction", methods=["POST"])
def add_transaction():
    # 获取表单数据
    debit_name = request.form.get("debit_account")
    credit_name = request.form.get("credit_account")
    direction = request.form.get("direction", type=int, default=1)  # 默认值为1
    details = request.form.get("details", "")
    try:
        result = session.get("invoice_data", {})
        # 如果用户有输入交易详情，则添加到结果中
        if details:
            result["details"] = details
        # 打开 GnuCash 文件（确保未被占用）
        if add_transaction_from_dict(debit_name, credit_name, direction, result):
            return redirect(url_for("success"))
    except Exception as e:
        return f"错误: {str(e)}", 500


@app.route("/success")
def success():
    return render_template("success.html")


if __name__ == "__main__":
    os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
    app.run(debug=True)
